package com.accenture.portal.controller.questionnaire;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.accenture.portal.model.User;
import com.accenture.portal.model.questionnaire.Answer;
import com.accenture.portal.model.questionnaire.Option;
import com.accenture.portal.model.questionnaire.Questionnaire;
import com.accenture.portal.service.UserService;
import com.accenture.portal.service.questionnaire.AnswerService;
import com.accenture.portal.service.questionnaire.QuestionnaireService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class AnswerController {
	
	@Autowired
	AnswerService answerService;
	
	@Autowired
	QuestionnaireService questionnaireService;
	
	@Autowired
	UserService userService;
	
	/**获取当前用户已保存的问卷列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getSavedQuestionnaireByUser.action")
	public void getSavedQuestionnaireByUser(HttpServletRequest request,HttpServletResponse response,Model model) {
		
		Boolean answerType=false;//标记为"保存"类型
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		List<Questionnaire> savedQuestionnaireList = answerService.getAnswerSaved(answerUser, answerType);
		
		JSONArray json = JSONArray.fromObject(savedQuestionnaireList);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**获取当前用户已经提交的问卷列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getSubmittedQuestionnaireByUser.action")
	public void getSubmittedQuestionnaireByUser(HttpServletRequest request,HttpServletResponse response,Model model) {
		
		Boolean answerType=true;//标记为"提交"类型
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		List<Questionnaire> submittedQuestionnaireList = answerService.getAnswerSaved(answerUser, answerType);
		
		JSONArray json = JSONArray.fromObject(submittedQuestionnaireList);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**获取最新问卷列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getNewQuestionnaireByUser.action")
	public void getNewQuestionnaireByUser(HttpServletRequest request,HttpServletResponse response,Model model) {
		
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		List<Questionnaire> newQuestionnaireList=answerService.getNewQuestionnaireByUser(answerUser);
		
		JSONArray json = JSONArray.fromObject(newQuestionnaireList);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**保存问卷
	 * @param checkedId
	 * @param textareaId1
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "saveQuestionnaireAnswer.action")
	public void saveQuestionnaireAnswer(@RequestParam("checkedId") String checkedId,@RequestParam("textareaId") String textareaId1,
	HttpServletRequest request, HttpServletResponse response, Model model) {
		String textareaId="";
		try {
			
//			textareaId = java.net.URLDecoder.decode(textareaId1, "utf-8");
			textareaId = new String(textareaId1.getBytes("iso-8859-1"),"utf-8");//转为UTF-8编码，问答题答案带中文
//			String newparam2 = new String(test.getBytes("iso-8859-1"),"utf-8");
			System.out.println();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Integer user_id=((User)request.getSession().getAttribute("user")).getUser_id();
		Integer questionnaireId = (Integer)request.getSession().getAttribute("questionnaireId");
		if(checkedId!=""){
		String optionMulti[] = checkedId.split(",");//分割成单个选项
		for (Integer i = 0; i < optionMulti.length; i++) {
			Answer answer = new Answer();
			String answerMulti[] = optionMulti[i].split(":");//分割选项id和问题id
			Integer optionId=Integer.valueOf(answerMulti[0]);
			answer.setAnswerOption(optionId);
			Integer questionId=Integer.valueOf(answerMulti[1]);
			answer.setAnswerQuestion(questionId);
			answer.setAnswerQuestionnaire(questionnaireId);
			answer.setAnswerUser(user_id);
			answer.setAnswerType(false);
			answerService.addOptionAnswer(answer);//保存选择题答案
		}
		}
		
		if(textareaId!=""){
		String textMulti[] = textareaId.split(",");//分割为单个答案
		for (Integer i = 0; i < textMulti.length; i++) {
			Answer answer = new Answer();
			String answerMulti[] = textMulti[i].split(":");
			String answerText=answerMulti[0];
//			answer.setAnswerText("我是中文");
			answer.setAnswerText(answerText);
			Integer questionId=Integer.valueOf(answerMulti[1]);
			answer.setAnswerQuestion(questionId);
			answer.setAnswerQuestionnaire(questionnaireId);
			answer.setAnswerUser(user_id);
			answer.setAnswerType(false);
			answerService.addTextAnswer(answer);//保存问答题答案
		}
		}
	}
	
	/**提交问卷
	 * @param checkedId
	 * @param textareaId1
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "submitQuestionnaireAnswer.action")
	public void submitQuestionnaireAnswer(@RequestParam("checkedId") String checkedId,@RequestParam("textareaId") String textareaId1,
	HttpServletRequest request, HttpServletResponse response, Model model) {
		String textareaId="";
		try {
			
//			textareaId = java.net.URLDecoder.decode(textareaId1, "utf-8");
			textareaId = new String(textareaId1.getBytes("iso-8859-1"),"utf-8");//转为UTF-8编码，问答题答案带中文
//			String newparam2 = new String(test.getBytes("iso-8859-1"),"utf-8");
			System.out.println();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Integer user_id=((User)request.getSession().getAttribute("user")).getUser_id();
		Integer questionnaireId = (Integer)request.getSession().getAttribute("questionnaireId");
		String optionMulti[] = checkedId.split(",");////分割成单个选项
		for (Integer i = 0; i < optionMulti.length; i++) {
			Answer answer = new Answer();
			String answerMulti[] = optionMulti[i].split(":");//分割选项id和问题id
			Integer optionId=Integer.valueOf(answerMulti[0]);
			answer.setAnswerOption(optionId);
			Integer questionId=Integer.valueOf(answerMulti[1]);
			answer.setAnswerQuestion(questionId);
			answer.setAnswerQuestionnaire(questionnaireId);
			answer.setAnswerUser(user_id);
			answer.setAnswerType(true);
			answerService.addOptionAnswer(answer);
		}
		
		String textMulti[] = textareaId.split(",");//分割为单个答案
		for (Integer i = 0; i < textMulti.length; i++) {
			Answer answer = new Answer();
			String answerMulti[] = textMulti[i].split(":");
			String answerText=answerMulti[0];
			answer.setAnswerText(answerText);
			Integer questionId=Integer.valueOf(answerMulti[1]);
			answer.setAnswerQuestion(questionId);
			answer.setAnswerQuestionnaire(questionnaireId);
			answer.setAnswerUser(user_id);
			answer.setAnswerType(true);
			answerService.addTextAnswer(answer);
		}
	}
	
	
	/**获取问答题的答案
	 * @param questionId
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getAnswerTextByUserIdAndQuestionId.action")
	public void getAnswerTextByUserIdAndQuestionId(@RequestParam("questionId") String questionId,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		Integer answerQuestion=Integer.valueOf(questionId);
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		Answer answerText=answerService.getAnswerTextByUserIdAndQuestionId(answerUser, answerQuestion);
//		if(answerText==null){
//			answerText="";
//		}
		
		JSONObject json = JSONObject.fromObject(answerText);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**获取问答题的答案2
	 * @param questionId
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getAnswerTextByUserIdAndQuestionId2.action")
	public void getAnswerTextByUserIdAndQuestionId2(
			@RequestParam("questionId") String questionId,
			@RequestParam("chosedUser") Integer chosedUser,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		Integer answerQuestion=Integer.valueOf(questionId);
		Integer answerUser=chosedUser;//获取当前user_id
		Answer answerText=answerService.getAnswerTextByUserIdAndQuestionId(answerUser, answerQuestion);
//		if(answerText==null){
//			answerText="";
//		}
		
		JSONObject json = JSONObject.fromObject(answerText);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**获取选择题的答案
	 * @param optionId
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getAnswerByUserIdAndOptionId.action")
	public void getAnswerByUserIdAndOptionId(@RequestParam("optionId") String optionId,HttpServletRequest request,HttpServletResponse response,Model model) {
		Integer answerOption=Integer.valueOf(optionId);
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		Answer answerText=answerService.getAnswerByUserIdAndOptionId(answerUser, answerOption);
		
		JSONObject json = JSONObject.fromObject(answerText);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**获取选择题的答案2
	 * @param optionId
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "getAnswerByUserIdAndOptionId2.action")
	public void getAnswerByUserIdAndOptionId2(
			@RequestParam("optionId") String optionId,
			@RequestParam("chosedUser") Integer chosedUser,
			HttpServletRequest request,HttpServletResponse response,Model model) {
		Integer answerOption=Integer.valueOf(optionId);
		Integer answerUser=chosedUser;//获取当前user_id
		Answer answerText=answerService.getAnswerByUserIdAndOptionId(answerUser, answerOption);
		
		JSONObject json = JSONObject.fromObject(answerText);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**删除此问卷当前用户保存过的答案，用在提交或再次保存之前
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "deleteAnswerByUserAndQuestionnaire.action")
	public void deleteAnswerByUserAndQuestionnaire(HttpServletRequest request,HttpServletResponse response,Model model) {
		Integer answerQuestionnaire = (Integer)request.getSession().getAttribute("questionnaireId");
		Integer answerUser=((User)request.getSession().getAttribute("user")).getUser_id();//获取当前user_id
		answerService.deleteAnswerByUserAndQuestionnaire(answerUser, answerQuestionnaire);
	}
	

	
    /**  
     * 根据userId获取用户，用在后台问卷编辑页面，显示已提交用户名
     * @author kaizhe.yang
     * @param id  
     * @param request  
     * @return  
     */  
    @RequestMapping("getUserById.action")  
    public void getUserById(@RequestParam("userId")int userId, HttpServletRequest request,HttpServletResponse response, Model model){ 
        User user=userService.findById(userId);
        
        JSONObject json = JSONObject.fromObject(user);
		String result = json.toString();
		try {
			response.getWriter().write(result);
			response.getWriter().flush();//清空缓冲区，完成写入
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
